package com.zmx.job.admin.core.thread;

import com.zmx.core.dto.RequestDataInfo;
import com.zmx.core.dto.ReturnT;
import com.zmx.core.utils.JobRemotingUtil;
import com.zmx.job.admin.core.conf.MallAdminConfig;
import com.zmx.job.admin.core.nodedistribute.JobRouteStrategyInfo;
import com.zmx.job.admin.core.nodedistribute.NodeDistributeHelper;
import com.zmx.job.admin.enums.RoutStrategyEnum;
import lombok.extern.slf4j.Slf4j;
import org.quartz.Job;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;

/**
 * @Description: 任务分发服务
 * @ClassName: JobSendHelper
 * @Author zhaomxr
 * @Date 2021-12-21 14:30
 */
@Slf4j
@Component
public class JobSendHelper {

    private static String node = "";

    @Async
    public void send(MallAdminConfig mallAdminConfig, RoutStrategyEnum strategyEnum, RequestDataInfo requestDataInfo, int failRetryCount) {
        //开始分发任务
        node = NodeDistributeHelper.getNode(strategyEnum);
        if (StringUtils.isEmpty(node)) {
            log.info("当前无可用节点！");
            return;
        }

        ReturnT returnT = postBody(mallAdminConfig.getRequestUrlPrefix() + node, requestDataInfo, 500);
        log.info("postBody return data：{}", returnT == null ? null : returnT.toString());

        //开启重试机制 返回状态码 code=333代表任务仍在运行
        if (returnT == null || (returnT.getCode() != 200 && returnT.getCode() != 333)) {
            int retryCount = failRetryCount;
            if (retryCount > 0) {
                while (retryCount > 0) {
                    log.info("postBody retry number of {}", retryCount);
                    ReturnT returnT1 = postBody(mallAdminConfig.getRequestUrlPrefix() + node, requestDataInfo, 500);
                    log.info("postBody return data：{}", returnT == null ? null : returnT.toString());
                    if (returnT1 != null && returnT1.getCode() == 200) {
                        break;
                    }

                    retryCount--;
                }
            }
        }
    }

    private ReturnT postBody(String url, RequestDataInfo requestDataInfo, int timeout) {
        ReturnT returnT = JobRemotingUtil.postBody(url, requestDataInfo, timeout);

        //如果任务分发成功，记录当前任务与分发节点关系到JobRouteStrategyInfo中
        if (returnT != null && (returnT.getCode() == 200 || returnT.getCode() == 333)) {
            JobRouteStrategyInfo.setJobInstance(requestDataInfo.getValue(), node);
        }
        
        return returnT;
    }
}